<template>
  <div>
    <n-space mb-4>
      <n-button type="primary" @click="handleAddUser">新建用户</n-button>
    </n-space>
    <n-data-table :columns="columns" :data="data" />

    <edit
      v-model:showModal="showModal"
      :currentUser="currentUser"
      :type="opType"
      @submit-callback="getData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, h } from "vue";
import { NSpace, NButton, NDataTable } from "naive-ui";
import { Icon } from "@iconify/vue";
import { getUserList, deleteUser } from "@/api/user";
import type { UserModel } from "@/api/user/model";
import Edit from "./components/Edit.vue";
import { dialog, message } from "@/utils/message";
import dayjs from "dayjs";

const showModal = ref(false);
const opType = ref<"add" | "edit" | "password">("add");
const currentUser = ref<UserModel>({
  id: 0,
  username: "",
  nickname: "",
  email: "",
  is_super: 0,
});

const columns = ref([
  {
    title: "账号",
    key: "username",
  },
  {
    title: "用户名",
    key: "nickname",
  },
  {
    title: "创建时间",
    key: "created_at",
    render(row: UserModel) {
      return dayjs(row.created_at).format("YYYY-MM-DD HH:mm:ss");
    },
  },
  {
    title: "操作",
    key: "action",
    render(row: any) {
      return h(NSpace, [
        h(
          NButton,
          {
            type: "warning",
            size: "tiny",
            onClick: () => handleEditPassword(row),
          },
          { default: () => [h(Icon, { icon: "ph:password" })] },
        ),
        h(
          NButton,
          {
            type: "primary",
            size: "tiny",
            onClick: () => handleEditUser(row),
          },
          { default: () => [h(Icon, { icon: "mingcute:edit-line" })] },
        ),
        h(
          NButton,
          {
            type: "error",
            size: "tiny",
            onClick: () => handleDeleteUser(row),
          },
          { default: () => [h(Icon, { icon: "mingcute:delete-line" })] },
        ),
      ]);
    },
  },
]);

const data = ref<UserModel[]>([]);

const handleAddUser = () => {
  showModal.value = true;
  opType.value = "add";
};

const handleEditUser = (row: UserModel) => {
  currentUser.value = row;
  showModal.value = true;
  opType.value = "edit";
};

const handleEditPassword = (row: UserModel) => {
  currentUser.value = row;
  opType.value = "password";
  showModal.value = true;
};

const handleDeleteUser = (row: UserModel) => {
  dialog.error({
    title: "确定删除该用户吗？",
    content: "删除后将无法恢复",
    positiveText: "删除",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        await deleteUser(row.id!);
        message.success("删除成功");
        getData();
      } catch (_) {
        message.error("删除失败");
      }
    },
  });
};

const getData = async () => {
  const res = await getUserList();
  if (res.code === 200) {
    data.value = res.data;
  } else {
    message.error(res.message);
  }
};
getData();
</script>
